﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using OfficeOpenXml;
using AtletIS.Shared.Data.aDbDataSetTableAdapters;
using System.Data;
using System.Windows.Forms;

namespace AtletIS.Shared.Helpers
{
    public static class ChipTagsExportHelper
    {
        public static ChipTagsTableAdapter taChipTags = new ChipTagsTableAdapter();
        
        public static void Export(int groupId)
        {
            try
            {
                FileInfo fi = new FileInfo("ChipTagsExport.xlsx");

                if (fi.Exists)
                    fi.Delete();

                // Export to Excel file
                ExcelPackage pkg = new ExcelPackage(fi);
                ExportChipTags(pkg, groupId);

                // Save, run
                pkg.Save();
                pkg.Dispose();
                System.Diagnostics.Process.Start(fi.FullName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Chip Tags Export", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private static void ExportChipTags(ExcelPackage pkg, int groupId)
        {
            ExcelWorksheet ws = pkg.Workbook.Worksheets.Add("ChipTags");
            
            // Header
            ws.Cells["A1"].Value = "CHIP_TAG";
            ws.Cells["B1"].Value = "ST_NUM";
            ws.Cells["A1:B1"].Style.Font.Bold = true;

            // Get data
            DataTable dtChipTags = DatabaseHelper.GetChipTagsByGroupId(groupId); 
            // taChipTags.GetByGroupId(groupId);

            int row = 2;
            foreach (var item in dtChipTags.Select(null, "StartNumber"))
            {
                ws.Cells["A" + row.ToString()].Value = item["ChipTag"].ToString();
                ws.Cells["B" + row.ToString()].Value = item["StartNumber"];

                row += 1;
            }

            // Fit columns
            ws.Cells["A1:B" + row.ToString()].AutoFitColumns();

            
 
        }




    }
}
